package org.example.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * 验证码生成工具类
 */
public class CaptchaUtil {
    
    private static final String CHARS = "ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";
    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 4;
    
    /**
     * 生成验证码图片和文本
     */
    public static class CaptchaResult {
        private String code;
        private byte[] imageBytes;
        
        public CaptchaResult(String code, byte[] imageBytes) {
            this.code = code;
            this.imageBytes = imageBytes;
        }
        
        public String getCode() {
            return code;
        }
        
        public byte[] getImageBytes() {
            return imageBytes;
        }
    }
    
    /**
     * 生成验证码
     */
    public static CaptchaResult generateCaptcha() throws IOException {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        
        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        
        // 生成验证码文本
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        
        // 设置字体
        g.setFont(new Font("Arial", Font.BOLD, 20));
        
        for (int i = 0; i < CODE_LENGTH; i++) {
            char c = CHARS.charAt(random.nextInt(CHARS.length()));
            code.append(c);
            
            // 设置随机颜色
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            
            // 绘制字符
            g.drawString(String.valueOf(c), 20 + i * 20, 25);
        }
        
        // 添加干扰线
        for (int i = 0; i < 5; i++) {
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            g.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT), 
                      random.nextInt(WIDTH), random.nextInt(HEIGHT));
        }
        
        g.dispose();
        
        // 转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        
        return new CaptchaResult(code.toString(), baos.toByteArray());
    }
}
